package com.hdu.service;

import com.alibaba.fastjson.JSON;
import com.hdu.config.DelayTaskConfig;
import javafx.scene.layout.VBox;
import lombok.val;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.alibaba.fastjson.JSON.parseObject;
import static java.util.Optional.ofNullable;


@Component
public class RedisService {

    private final DelayTaskConfig delayTaskConfig;


    private Jedis JEDIS;
    private static final String OK = "OK";
    private static final int SINGLE_QUERY_LEN = 100;

    public RedisService(DelayTaskConfig delayTaskConfig) {
        this.delayTaskConfig = delayTaskConfig;
    }


    @PostConstruct
    public void init() {
        JEDIS = new Jedis(delayTaskConfig.getRedisIp(), delayTaskConfig.getRedisPort());
        JEDIS.auth(delayTaskConfig.getDbPassword());
    }


    public boolean delete(String key) {
        return JEDIS.del(key) == 1;
    }


    public <T> List<T> zrangeByScore(Class<T> clazz, String key, long start, long end) {
        return JEDIS.zrangeByScore(key, start, end).stream()
                .map(s -> parseObject(s, clazz))
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }

    public boolean set(String key, String value) {
        return OK.equals(JEDIS.set(key, value));
    }

    public boolean zadd(String key, double score, String member) {
        return JEDIS.zadd(key, score, member) == 1;
    }

    public boolean zrem(String key, String member) {
        return JEDIS.zrem(key, member) == 1;
    }

    public <T> T rpop(String key, Class<T> clazz) {
        return ofNullable(JEDIS.rpop(key)).map(s -> parseObject(s, clazz)).orElse(null);
    }

    public void lpush(String key, String value) {
        JEDIS.lpush(key, value);
    }

    @SuppressWarnings("all")
    public List<String> selectKeysByPattern(String pattern) {
        List<String> res = new ArrayList<>();
        val scanParams = new ScanParams().match(pattern).count(SINGLE_QUERY_LEN);
        String cursor = "0";
        do {
            val scanResult = JEDIS.scan(cursor, scanParams);
            cursor = String.valueOf(scanResult.getCursor());
            res.addAll(scanResult.getResult());
        } while (!cursor.equals("0"));
        return res;
    }


}
